---
layout : doc
title : Controllers in Phoenix
permalink: docs\Controllers.html
---

## MVC Introduction

There are quite a few types of the MVC pattern floating around, Phoenix is modelled after ASP.net's implementation, not the classic small-talk style MVC pattern.

It all starts off with a Controller, and an Action.

    public class HomeController : Controller
    {
        public ActionResult Main()
        {
            return Page(new MainViewModel());
        }
    }

An **action** is simply a method on a class which inherits from Controller. The Controller returns an ActionResult, there are helper methods in the controller base class which let you do this with ease.

Phoenix supports the following controller actions out of the box:

<table border="1">
    <tr>
        <th>Result Type</th>        
        <th>Purpose</th>
    </tr>
    
    <tr>
        <td>DoNothingResult</td>        
        <td>Completes the controller action without taking action. Same effect as returning null from a controller action</td>
    </tr>
    <tr>
        <td>MessageBoxActionResult</td>        
        <td>Shows a windows message box, optionally supports a callback so when the user interacts you can be notified</td>
    </tr>
    <tr>
        <td>NavigateBackActionResult</td>        
        <td>Causes the current navigation frame to navigate backwards. See [navigation](Navigation.html) for more information</td>
    </tr>
    <tr>
        <td>PageActionResult</td>        
        <td>Causes a navigation to a view with the same name as the currently executing controller action, optionally can pass a viewmodel which will be set as the views DataContext</td>
    </tr>
    <tr>
        <td>RedirectActionResult</td>        
        <td>Redirects execution to another controller action, executed as part of the current executing request (impacts people waiting on the execution to finish, and possibly filters)</td>
    </tr>
    <tr>
        <td>ReturnResultActionResult</td>        
        <td>Returns a result to the invoker requesting data from an action result. See [returning results](#returningResults) for more information.</td>
    </tr>
    <tr>
        <td>ReturnResultActionResult</td>        
        <td>Returns a result to the invoker requesting data from an action result. See [returning results](#returningResults) for more information.</td>
    </tr>
    <tr>
        <td>ViewActionResult</td>        
        <td>Base class for view related action results (Navigating to pagePage, showing Window). Inherit from this class to create more view related results.</td>
    </tr>
    <tr>
        <td>WindowActionResult</td>        
        <td>Shows a view as a window.</td>
    </tr>
</table>

## Asynchronous Actions

While actions in Phoenix are always executed off the UI Thread, Phoenix also supports asynchronous controller actions, which allows you to use the Task Parrallel library or the new async/await keywords inside your controller actions to make them fully asynchronous.

    public class HomeController : Controller
    {
        public async Task<ActionResult> Main()
        {
            var data = await someService.GetDataAsync();
            return Page(new MainViewModel(data));
        }
    }
    
## Returning Data from Action
One powerful feature of phoenix is the ability to return data to a previous view in an asynchronous manner. Take the scenario of selecting a customer:

    // On existing view, in SelectCustomerCommand 
    SelectedCustomer = await Controller<CustomerController>().InvokeWithResult<CustomerSelectionResult>(c=>SelectCustomer());

![Select Customer](/img/2Controllers.png)

    // CustomerController.cs
    public class CustomerController : Controller
    {
         public WindowActionResult SelectCustomer()
         {
             return Window(new SelectCustomerViewModel());
         }
    }
    
This gives us:

![Select Customer Window](/img\2Controllers1.png)

In our OkCommand handler:

    public void Ok()
    {
        Context.CompletionSource.SetResult(new CustomerSelectionResult(SelectedCustomer));
        //Close window
    }

And on our existing view:

![2Controllers2](/img\2Controllers2.png)

This gives us a fully asynchronous way to return data from a reusable view. You can also return data directly from the controller action with code something like:

    public class CustomerController : Controller
    {
         public ActionResult SelectCustomer()
         {
             return Result(new CustomerSelectionResult(cancelled: true));
         }
    }

Notice that we never have to worry about locking things up, this also works with navigation, and after you set the result you can simply navigate back and the updated view will be there!

## Action Execution Pipeline

There are a few stages to executing a controller action, and options. Firstly, a controller action is executed in the context of a [Navigation Frame](NavigationFrames.html). By default controller actions are treated as foreground actions. This means only a single foreground action can be executing against a Navigation Frame at a time. Multiple actions will be queued against a frame and execute one by one.

There are a number of InvokeOptions which can change the behaviour of Phoenix:, these are flags, and multiple can be used at a time.

<table border="1">
    <tr>
        <th>InvokeOptions</th>        
        <th>Behaviour</th>
    </tr>
    
    <tr>
        <td>None</td>        
        <td>Normal foreground (limited to single action executing against a frame at a time) action, this will show a progress busy, disable UI elements in the navigation frame, and put a opacity overlay. See [navigation frames](NavigationFrames.html) for more information about this behaviour. </td>
    </tr>
    <tr>
        <td>NoProgress</td>        
        <td>Foreground action invocation, but the NavigationFrame will not have any visual feedback to the user, or block the navigation frame from user interaction. Useful if you want to show your own progress bar controlled by the view, rather than cross cut.</td>
    </tr>
    <tr>
        <td>InBackground</td>        
        <td>Background actions have no visual feedback to the user, and can multiple actions concurrently.</td>
    </tr>
    <tr>
        <td>UseWeakReference</td>        
        <td>By default a navigation frames journal holds onto the view and view model until it is popped off the 'back stack'. If your application is very heavy with navigation this can cause memory pressure. This option means that Phoenix will hold onto the view via weak reference allowing that view to be garbage collected. If that happens when you navigate back to that view, Phoenix will re-invoke the controller action, restore any state, then show that view (use the Transient(()=>MyProperty) helper to flag a property as transient state). This works for both WPF and WP7, see [Lifecycle](Lifecycle.html) for more information about how phoenix manages view's lifetime, and how that works with Tombstoning on WP7.</td>
    </tr>
</table>

### Stages

<table border="1">
    <tr>
        <th>Execution Stage</th>        
        <th>Responsibility</th>
        <th>Executed on</th>
    </tr>
    
    <tr>
        <td>Queue if Busy</td>        
        <td>For foreground invocations, Phoenix checks if the NavigationFrame is busy, if it is, this request is queued for execution after the current action has completed execution.</td>
        <td>Background</td>
    </tr>
    <tr>
        <td>Begin operation</td>        
        <td>This notifies the NavigationFrame that an operation is happening, this can be foreground or background, then the navigation frame will decide if progress/feedback needs to be given to the user.</td>
        <td>UI Thread</td>
    </tr>
    <tr>
        <td>Action Executing</td>        
        <td>Invokes all action filters `OnActionExecuting` method</td>
        <td>Background</td>
    </tr>
    <tr>
        <td>Execute Action</td>        
        <td>Invokes your action on your controller</td>
        <td>Background</td>
    </tr>
    <tr>
        <td>Action Executed</td>        
        <td>Invokes all action filters `OnActionExecuted` method, you can handle exceptions or change the result here.</td>
        <td>Background</td>
    </tr>
    
    <tr>
        <td>Exception Filters</td>        
        <td>If an exception occurred while executing your controller action, you can handle it here. Action filters have the first chance to handle the exception, so if they handle the exception the exception filters will not be executed.</td>
        <td>Background</td>
    </tr>
    <tr>
        <td>Result Executing</td>        
        <td>Executed before the action result is executed</td>
        <td>Background</td>
    </tr>
    <tr>
        <td>Execute Result</td>        
        <td>Execute the ActionResult</td>
        <td>Background</td>
    </tr>
    <tr>
        <td>Result Executed</td>        
        <td>Can be used to manipulate the result, for instance a filter which applies view conventions</td>
        <td>Background</td>
    </tr>
    <tr>
        <td>Operation Completed</td>        
        <td>Notifies the NavigationFrame that the operation has complete. This will hide the progress bars and reenable the NavigationFrame.</td>
        <td>UI Thread</td>
    </tr>
    <tr>
        <td>Result Completion Steps</td>        
        <td>Action results can opt in to having completion steps by inheriting from the `IHaveCompletionSteps` interface which is executed on the UI Thread, this can be used to create/show views and do other operations that are on the UI Tread</td>
        <td>UI Thread</td>
    </tr>
    <tr>
        <td>Runs next enqueued action</td>        
        <td>If there has been an operation queued, it will be executed.</td>
        <td>Background</td>
    </tr>
</table>

